<!--
 * @Author: Bobby
 * @Date: 2021-12-30 10:01:42
 * @LastEditTime: 2023-09-21 17:02:05
 * @LastEditors: 甯左龙 1173405584@qq.com
 * @Description:
 * @FilePath: \wms-v2\src\ve\elements\form\uiSelect\uiSelect.vue
 * CIMC-V2
-->
<template>
  <UiFormItem :class="{ hidden: info.extension.hidden.value || conditionProperty.hidden }" :info="info">
    <!-- <span>{{ optionList }}</span> -->
    <el-select
      :ref="info._id"
      v-model="formDataModel"
      v-ui-ref="vSetRef"
      :allow-create="info.extension.allowCreate && info.extension.allowCreate.value"
      class="w-full"
      clearable
      :disabled="info.extension.disabled.value || conditionProperty.disabled"
      filterable
      :multiple="info.extension.multiple.value"
      :placeholder="translateTitle('Ve.elements.请选择')"
      :size="info.extension.size ? info.extension.size.value : 'mini'"
      @blur="funblur"
      @change="handleChange"
      @keyup.enter="handleEnter"
      @visible-change="handleVisibleChange"
    >
      <!-- 如果是多选状态则添加一个全选选项 -->
      <!-- <span v-if="info.extension.multiple.value">全选</span> -->
      <el-checkbox v-if="info.extension.multiple.value" v-model="allChecked" class="ml-4" :indeterminate="isIndeterminate" @change="selectAllChange">
        全选
      </el-checkbox>
      <el-option
        v-for="item in optionList"
        :key="`${item[info.extension.valueField.value]}_${postfixKey}`"
        :label="item[info.extension.labelField.value] || 'label'"
        :value="item[info.extension.valueField.value] || 'value'"
      >
        <span>{{ item[info.extension.labelField.value] }}</span>
      </el-option>
    </el-select>
  </UiFormItem>
</template>
<script>
  import { translateTitle } from '@/utils/i18n'
  import request from '@/utils/request'
  import { GFCD } from '@/utils/utils'
  import isEmpty from 'lodash/isEmpty'
  import merge from 'lodash/merge'
  import trim from 'lodash/trim'
  import isArray from 'lodash/isArray'
  import cloneDeep from 'lodash/cloneDeep'
  import isString from 'lodash/isString'
  import { customAlphabet } from 'nanoid'
  import { defineComponent } from 'vue'
  import { processingConstant, replaseRegVariable } from '@ve/utils/utils'
  import { UiMixin, ElementsFormMixin, RefsInjectMixin, ConditionMixin } from '@ve/mixin'
  export default defineComponent({
    name: 'UiSelect',
    components: {},
    mixins: [UiMixin, ElementsFormMixin, RefsInjectMixin, ConditionMixin],
    data() {
      return {
        optionList: [],
        lastNewval: {},
        postfixKey: 'aa',
        dataSourceChangeTimeOut: '',
        allChecked: false,
        isIndeterminate: false,
      }
    },
    computed: {
      optionConfigData() {
        return this.info.extension.optionConfig.value
      },
      valueField() {
        return this.info.extension.valueField.value
      },
    },
    watch: {
      optionConfigData: {
        handler(newVal) {
          // console.log('下拉组件的  lastNewval  -------- ', newVal)
          this.optionList = newVal || []
        },
      },
      formDataModel: {
        handler(newVal) {
          // console.log('下拉组件的  formDataModel  -------- ', newVal)
          // 触发往表单带值
          if (this.info.extension?.getOutKey?.value) {
            const outKeyArr = this.info.extension?.getOutKey?.value.split(',')
            const formModel =
              this.$store.state.preview?.pagesMods[this.locationPageId] && this.$store.state.preview?.pagesMods[this.locationPageId][this.formId]
            if (formModel) {
              for (let i = 0; i < outKeyArr.length; i++) {
                for (let index = 0; index < this.optionList.length; index++) {
                  if (this.optionList[index][this.valueField] === newVal) {
                    formModel.data.formData[trim(outKeyArr[i])] = this.optionList[index][trim(outKeyArr[i])]
                  }
                }
              }
            }
          }
        },
      },
      optionList: {
        handler(newVal) {
          // 触发往表单带值
          if (this.info.extension?.getOutKey?.value) {
            // console.log('jin1')
            const outKeyArr = this.info.extension?.getOutKey?.value.split(',')
            const formModel =
              this.$store.state.preview?.pagesMods[this.locationPageId] && this.$store.state.preview?.pagesMods[this.locationPageId][this.formId]
            if (formModel) {
              // console.log('jin2')
              for (let i = 0; i < outKeyArr.length; i++) {
                for (let index = 0; index < this.optionList.length; index++) {
                  if (this.optionList[index][this.valueField] === this.formDataModel) {
                    // console.log('jin3', formModel)
                    formModel.data.formData[trim(outKeyArr[i])] = this.optionList[index][trim(outKeyArr[i])]
                  }
                }
              }
            }
          }
          // 判断是否全选(当组件可多选并且配置了默认全选时)
          if (this.info.extension.multiple.value && this.info.extension.selectAll && this.info.extension.selectAll.value) {
            let valueList = []
            newVal.forEach((optionItem) => {
              valueList.push(optionItem[this.valueField])
            })
            this.$nextTick(() => {
              this.formDataModel = valueList
              // 触发条件判断值改变
              this.setPageModulesState('value', this.formDataModel)
            })
          }
        },
      },
    },
    // created() {
    //   this.optionList = this.info.extension.optionConfig.value
    // },
    created() {
      // if (this.info._id === 'uiSelect_m9s9o5') console.log('组件创建前 ================== ')
      // 判断是否有配置获取选项
      if (this.hasPreview && this.info.extension.api.value) {
        // 如果配置了默认不请求 则取消请求
        if (this.info.extension.dontRequest && this.info.extension.dontRequest.value) return
        this.requestOptionList()
      } else {
        this.optionList = this.info.extension.optionConfig.value
      }
    },
    methods: {
      translateTitle,
      requestOptionList(cb) {
        let requestDataObj = {}
        isArray(this.info.extension.requestData.value) &&
          this.info.extension.requestData.value.forEach((item) => {
            let itemVal = item.value
            if (/#{.*?}/g.test(item.value)) {
              itemVal = replaseRegVariable(itemVal, this.info.data.formData)
            }
            requestDataObj[item.key] = processingConstant(this, itemVal)
          })
        let options = {
          api: this.info.extension.api.value,
          method: this.info.extension.method.value,
          getDataKey: this.info.extension.getDataKey.value,
          data: merge(requestDataObj, this.info.data.formData),
        }
        if (!trim(options.api)) return
        this.request(options, cb)
      },
      request(options = {}, cb = null) {
        this.loading = true
        let getDataKey = options.getDataKey
        //发起请求
        return request({
          url: GFCD('dams', 'domain') + options.api,
          method: 'post',
          data: {
            data: JSON.stringify(options.data),
            method: options.method,
          },
        }).then((res) => {
          this.loading = false
          //解密
          // console.log(decryptd(res))
          // this.getInfo.data.requestData = isEmpty(getDataKey) ? res.data : res.data[getDataKey]
          let optionList = isEmpty(getDataKey) ? res.data.data || [] : res.data[getDataKey].data || []
          if (isArray(optionList)) {
            this.optionList = optionList
          } else {
            this.optionList = []
          }
          this.postfixKey = this.componentId()
          if (this.info.extension?.isDefault?.value?.key && this.info.extension?.isDefault?.value?.value) {
            let item = this.optionList.filter((el) => el[this.info.extension?.isDefault?.value?.key] == this.info.extension?.isDefault?.value?.value)
            if (this.info.extension.isDefault.value && item && item.length > 0) {
              if (item.length > 1 && this.info.extension?.multiple?.value) {
                this.formDataModel = item.map((el) => el[this.info.extension.valueField.value])
              } else {
                this.formDataModel = item[0][this.info.extension.valueField.value]
              }
            }
          }

          // 进行回调
          cb && cb(res)

          // console.log('this.optionList -------------------- ', this.optionList)
        })
      },
      handleChange() {
        this.$pub(`SplitpaneResized_${this.previewPageId()}`, true)
        // 触发条件判断值改变
        this.setPageModulesState('value', this.formDataModel)
        // 调用 change 事件
        this.onChange()
        // 判断全选状态
        if (this.info.extension.multiple.value) this.selectAllFunc()
      },
      funblur() {
        //select组件下拉框blur事件触发验证
        if (JSON.stringify(this.getInfo.extension.extendRule.value || {}) !== '{}') {
          this.vuiComponents[this.formId].ref.validateField([this.getInfo.extension.model.value])
        }
      },
      dataSourceChange(newval) {
        if (this.dataSourceChangeTimeOut) clearTimeout(this.dataSourceChangeTimeOut)
        this.dataSourceChangeTimeOut = setTimeout(() => {
          // 判断是否有值改变
          let changeFlag = false
          if (trim(this.info.dataSourceBind.getDataKey?.value)) {
            // 如果有获取数据Key 则判断获取的数据是否改变
            const keyList = this.info.dataSourceBind.getDataKey?.value.split(',')
            isArray(keyList) &&
              keyList.forEach((keyItem) => {
                keyItem = trim(keyItem)
                if (newval[keyItem] !== this.lastNewval[keyItem]) {
                  changeFlag = true
                }
              })
          } else {
            Object.keys(newval).map((v) => {
              if (newval[v] !== this.lastNewval[v]) {
                changeFlag = true
              }
            })
          }
          if (changeFlag) {
            this.lastNewval = cloneDeep(newval)
          } else {
            // 如果值未改变则不进行后续操作
            return
          }
          // console.log('this.lastNewval 22222222222222222', this.lastNewval)
          let _obj = {}
          Object.keys(this.getInfo.data.formData).map((v) => {
            _obj[v] = ''
          })
          let _mergeData = {}
          // 根据 getDataKey 筛选需要的数据
          // console.log('trim(this.dataSource.getDataKey)', trim(this.dataSource.getDataKey))
          if (!trim(this.info.dataSourceBind.getDataKey?.value)) {
            // 如果没有 getDataKey 则返回全量数据
            _mergeData = newval
          } else {
            const keyList = this.info.dataSourceBind.getDataKey?.value.split(',')
            isArray(keyList) &&
              keyList.forEach((item) => {
                item = trim(item)
                if (newval[item] !== undefined) {
                  // 如果传过来的对象里面没有要取得值 则丢弃
                  _mergeData[item] = newval[item]
                }
              })
          }
          let _data = isEmpty(_mergeData)
            ? _obj
            : {
                ...this.getInfo.data.formData,
                ..._mergeData,
              }
          // console.log('_mergeData ========= ', _mergeData)
          // console.log('_data ========= ', _data)
          this.getInfo.data.formData = _data
          // 请求数据
          this.requestOptionList()
        }, 500)
      },
      componentId() {
        const nanoid = customAlphabet('abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMN', 6)
        return nanoid()
      },
      handleEnter() {
        if (this.info.extension.multiple.value) {
          // 如果是可多选
          if ((!this.formDataModel || !this.formDataModel.length) && this.optionList.length) {
            this.formDataModel = [this.optionList[0][this.valueField]]
          }
        } else {
          if (!this.formDataModel && this.optionList.length) {
            // 如果没有值 则赋值为选项的第一项
            this.formDataModel = this.optionList[0][this.valueField]
          }
        }

        this.$handleEnter()
      },
      // 全选框改变
      selectAllChange(flag) {
        if (flag) {
          // 全选
          const valueList = []
          this.optionList.forEach((i) => {
            valueList.push(i[this.info.extension.valueField.value])
          })
          this.formDataModel = valueList
        } else {
          this.formDataModel = ''
        }
        this.isIndeterminate = false
      },
      handleVisibleChange(visible) {
        if (!visible || !this.info.extension.multiple.value) return
        // 弹窗打开时需要判断是否为全选状态
        this.selectAllFunc()
      },
      // 判断全选状态
      selectAllFunc() {
        let dataList = this.formDataModel || []
        if (this.formDataModel && isString(this.formDataModel)) {
          // 字符串类型值需要拆分
          dataList = this.formDataModel.split(',')
        }
        // 判断是否全选状态
        if (dataList.length === this.optionList.length) {
          this.allChecked = true
          this.isIndeterminate = false
        } else if (dataList.length) {
          // 有选中项但没有全选
          this.allChecked = false
          this.isIndeterminate = true
        } else {
          // 没有选择项
          this.allChecked = false
          this.isIndeterminate = false
        }
      },
    },
  })
</script>
<style lang="scss" scoped>
  :deep() .el-select .el-input .el-input__inner {
    width: 100% !important;
  }
</style>
